package cn.vinann.demo.controller;

import java.net.URL;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import com.alibaba.fastjson.JSON;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.googlecode.jsonrpc4j.ProxyUtil;

import cn.vinann.demo.api.ExampleServerAPI;
import cn.vinann.demo.common.HttpClientUtil;

/**
 * 主页
 * @author wn
 *
 */
@Controller
public class IndexController {

	@Autowired
    private ResourceUrlProvider resourceUrlProvider;
	
	/**
	 * 首页
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/")
	public String index(ModelMap modelMap,HttpServletRequest httpRequest,HttpServletResponse httpServletResponse){
		modelMap.addAttribute("now", new Date());
		Cookie[] cookies = httpRequest.getCookies();
		System.out.println(JSON.toJSONString(cookies));
		Cookie cookie = new Cookie("majun", "xiaoya");
	    cookie.setMaxAge(10); //设置cookie的过期时间是10s
	    httpServletResponse.addCookie(cookie);
		return "index";
	}
	
	@RequestMapping("/game")
	public String game(){
		return "game";
	}
	
	@ResponseBody
	@RequestMapping(value="/json")
	public String json(){
		"1".substring(10);
		return "json";
	}
	
	/**
	 * 静态资源版本管理
	 * @return
	 */
    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }
    
    @ResponseBody
	@RequestMapping(value="/t")
    public Integer t() throws Throwable{
    	JsonRpcHttpClient client = new JsonRpcHttpClient(
    		    new URL("http://192.168.82.63:8080/calculator"));
    	
    	Integer i = client.invoke("multiplier", new Object[] { 1, 2},Integer.class);
    	client.invoke("multiplier", new Object[] { 1, 2},Integer.class);
    	client.invoke("multiplier", new Object[] { 1, 2},Integer.class);
    	ExampleServerAPI serverAPI = ProxyUtil.createClientProxy(
    		    getClass().getClassLoader(),
    		    ExampleServerAPI.class,
    		    client);

    		i = serverAPI.multiplier(0, 1);
    	return i;
    }
	
}
